package io.adrainty.bolee.framework.web.converter;

import io.adrainty.bolee.framework.commons.basic.IEnum;
import jakarta.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>EnumConverter</p>
 *
 * @author AdRainty
 * @version V1.0.0
 * @description 枚举类转换
 * @since 2025/8/1 11:11:30
 */
public class EnumConverter<T extends IEnum> implements Converter<String, T> {

    private final Map<String, T> enumMap;

    public EnumConverter(Class<T> enumClass) {
        T[] constants = enumClass.getEnumConstants();
        this.enumMap = new HashMap<>(constants.length);
        for (T constant : constants) {
            this.enumMap.put(constant.getCode(), constant);
        }
    }

    @Override
    public T convert(@Nonnull String source) {
        if (StringUtils.isBlank(source)) return null;
        return enumMap.get(source);
    }

}
